import { getSessionStorage } from '@/router/common'
import { ElNotification } from 'element-plus'

class WebSocketService {
    constructor() {
        this.ws = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000; // 3秒
        this.isConnecting = false;
    }

    connect() {
        if (this.isConnecting) return;
        this.isConnecting = true;

        const user = getSessionStorage('teacher');
        if (!user) {
            console.error('用户未登录，无法建立WebSocket连接');
            this.isConnecting = false;
            return;
        }

        const wsUrl = `ws://localhost:8080/ws/${user.tTid}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.onopen = () => {
            console.log('WebSocket连接已建立');
            this.reconnectAttempts = 0;
            this.isConnecting = false;
        };

        this.ws.onclose = () => {
            console.log('WebSocket连接已关闭');
            this.isConnecting = false;
            this.reconnect();
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            this.isConnecting = false;
        };

        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                ElNotification({
                    title: '系统通知',
                    message: data.msg,
                    type: 'warning',
                    duration: 5000,
                    position: 'top-right'
                });
            } catch (error) {
                console.error('消息解析错误:', error);
            }
        };
    }

    reconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.error('WebSocket重连次数超过最大限制');
            return;
        }

        this.reconnectAttempts++;
        console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
        
        setTimeout(() => {
            this.connect();
        }, this.reconnectInterval);
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
    }

    send(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.error('WebSocket未连接，无法发送消息');
        }
    }
}

// 创建单例实例
const websocketService = new WebSocketService();
export default websocketService; 